<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>巡检单详情</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>
      
      <el-descriptions :column="2" border>
        <el-descriptions-item label="巡检单号">{{ inspectionRecord.recordCode }}</el-descriptions-item>
        <el-descriptions-item label="巡检计划">{{ inspectionRecord.planName || '无' }}</el-descriptions-item>
        <el-descriptions-item label="计划编号">{{ inspectionRecord.planCode || '无' }}</el-descriptions-item>
        <el-descriptions-item label="巡检设备">{{ inspectionRecord.equipmentName }}</el-descriptions-item>
        <el-descriptions-item label="巡检人">{{ inspectionRecord.inspectorName }}</el-descriptions-item>
        <el-descriptions-item label="巡检日期">
          {{ parseTime(inspectionRecord.inspectionDate, '{y}-{m}-{d}') }}
        </el-descriptions-item>
        <el-descriptions-item label="巡检状态">
          <el-tag :type="getStatusType(inspectionRecord.status)">
            {{ statusFormat(inspectionRecord) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ parseTime(inspectionRecord.startTime) || '未开始' }}
        </el-descriptions-item>
        <el-descriptions-item label="巡检结果" v-if="inspectionRecord.status === '2'">
          <el-tag :type="inspectionRecord.result === '0' ? 'success' : 'danger'">
            {{ inspectionRecord.result === '0' ? '正常' : '不合格' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="巡检结果" v-else>
          <span>待完成巡检</span>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ inspectionRecord.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">巡检项目列表</el-divider>
      
      <el-table :data="inspectionItems" border style="width: 100%; margin-bottom: 20px;" v-loading="itemsLoading">
        <el-table-column prop="itemName" label="巡检项名称" min-width="120" />
        <el-table-column prop="itemStandard" label="巡检标准" min-width="120" />
        <el-table-column prop="checkMethod" label="检查方法" min-width="120" />
      </el-table>

      <el-divider content-position="center">操作记录</el-divider>
      
      <el-table 
        :data="dateRecords" 
        border 
        style="width: 100%; margin-bottom: 20px;" 
        v-loading="dateRecordsLoading"
        @row-click="handleRowClick"
      >
        <el-table-column label="巡检日期" align="center" width="120">
          <template slot-scope="scope">
            {{ parseTime(scope.row.inspectionDate, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
        <el-table-column label="巡检状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
              {{ scope.row.status === '1' ? '已巡检' : '未巡检' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="巡检结果" align="center" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === '1'" :type="scope.row.result === '0' ? 'success' : 'danger'">
              {{ scope.row.result === '0' ? '正常' : '异常' }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="巡检时间" align="center" width="180">
          <template slot-scope="scope">
            {{ scope.row.status === '1' ? parseTime(scope.row.updateTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="180" />
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click.stop="handleViewDetail(scope.row)"
              v-if="scope.row.status === '1'"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 巡检详情对话框 -->
      <el-dialog :title="'巡检详情 - ' + parseTime(currentDateRecord.inspectionDate, '{y}-{m}-{d}')" :visible.sync="detailDialogVisible" width="800px">
        <div v-loading="detailLoading">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="巡检日期">{{ parseTime(currentDateRecord.inspectionDate, '{y}-{m}-{d}') }}</el-descriptions-item>
            <el-descriptions-item label="巡检结果">
              <el-tag :type="currentDateRecord.result === '0' ? 'success' : 'danger'" v-if="currentDateRecord.result">
                {{ currentDateRecord.result === '0' ? '正常' : '异常' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="巡检时间">{{ parseTime(currentDateRecord.updateTime) }}</el-descriptions-item>
            <el-descriptions-item label="巡检人员">{{ inspectionRecord.inspectorName }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ currentDateRecord.remark || '无' }}</el-descriptions-item>
          </el-descriptions>
          
          <el-divider content-position="center">巡检项目详情</el-divider>
          
          <el-table :data="dateDetailItems" border style="width: 100%; margin-bottom: 20px;">
            <el-table-column prop="itemName" label="巡检项名称" min-width="120" />
            <el-table-column label="巡检标准" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.standardValue || scope.row.itemStandard || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="巡检结果" align="center" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.result === '1' ? 'success' : 'danger'">
                  {{ scope.row.result === '1' ? '通过' : '未通过' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="150">
              <template slot-scope="scope">
                {{ scope.row.remark || scope.row.abnormalDesc || scope.row.suggestion || '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>

      <div class="action-buttons">
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getInspectionRecord } from "@/api/sb/inspectionRecord";
import { getDetailsByRecordId } from "@/api/sb/inspectionDetail";
import { getItemsByConfigId } from "@/api/sb/inspectionItem";
import { getInspectionConfig } from "@/api/sb/inspectionConfig";
import { getInspectionPlan } from "@/api/sb/inspectionPlan";
import { getByInspectionRecord, getByDate } from "@/api/sb/inspectionDateRecord";

export default {
  name: "InspectionRecordDetail",
  data() {
    return {
      // 巡检记录信息
      inspectionRecord: {},
      // 巡检项目列表
      inspectionItems: [],
      // 巡检状态选项
      statusOptions: [
        { dictLabel: '待巡检', dictValue: '0' },
        { dictLabel: '巡检中', dictValue: '1' },
        { dictLabel: '已完成', dictValue: '2' },
        { dictLabel: '已取消', dictValue: '3' }
      ],
      // 加载状态
      itemsLoading: false,
      // 操作记录
      dateRecords: [],
      dateRecordsLoading: false,
      // 巡检详情对话框
      detailDialogVisible: false,
      currentDateRecord: {
        inspectionDate: new Date(),
        result: '',
        updateTime: new Date(),
        remark: ''
      },
      detailLoading: false,
      dateDetailItems: []
    };
  },
  created() {
    const recordId = this.$route.params.id;
    this.getRecord(recordId);
  },
  methods: {
    /** 获取巡检记录详情 */
    getRecord(recordId) {
      getInspectionRecord(recordId).then(response => {
        if (response.code === 200) {
          this.inspectionRecord = response.data;
          console.log("获取到巡检记录详情:", this.inspectionRecord);
          
          // 获取巡检详情项
          this.getInspectionDetails(recordId);
          // 获取巡检日期记录
          this.getDateRecords(recordId);
        } else {
          this.$message.error("获取巡检记录详情失败");
        }
      }).catch(error => {
        console.error("获取巡检记录详情出错", error);
        this.$message.error("获取巡检记录详情出错");
      });
    },
    
    /** 获取巡检详情项列表 */
    getInspectionDetails(recordId) {
      this.itemsLoading = true;
      console.log("开始获取巡检详情项，recordId:", recordId);
      
      getDetailsByRecordId(recordId).then(response => {
        console.log("获取巡检详情项响应:", response);
        
        if (response.code === 200 && response.data && response.data.length > 0) {
          // 如果有详情数据，直接使用
          this.inspectionItems = response.data.map(item => {
            // 处理remark字段，使用abnormalDesc或suggestion作为备注
            const remark = item.abnormalDesc || item.suggestion || '';
            return {
              ...item,
              remark: remark
            };
          });
          console.log("处理后的巡检项目列表:", this.inspectionItems);
          this.itemsLoading = false;
        } else {
          console.log("没有找到巡检详情项，尝试从巡检计划获取配置项");
          // 如果没有详情数据，尝试从巡检计划获取配置项
          this.getItemsFromPlan();
        }
      }).catch(error => {
        console.error("获取巡检项目详情出错", error);
        // 尝试从巡检计划获取配置项
        this.getItemsFromPlan();
      });
    },

    /** 通过巡检计划获取巡检配置项 */
    getItemsFromPlan() {
      // 确保有计划ID
      if (!this.inspectionRecord.planId) {
        console.warn("没有找到关联的巡检计划ID");
        this.itemsLoading = false;
        return;
      }

      // 先获取巡检计划信息
      getInspectionPlan(this.inspectionRecord.planId).then(response => {
        if (response.code === 200 && response.data) {
          // 处理新的数据结构
          let plan;
          let configId;
          
          if (response.data.planInfo) {
            // 新的数据结构
            plan = response.data.planInfo;
            configId = plan.configId;
            console.log("使用新的数据结构获取巡检计划信息:", plan);
            
            // 如果响应中直接包含巡检项目，直接使用
            if (response.data.inspectionItems && response.data.inspectionItems.length > 0) {
              console.log("直接使用返回的巡检项目:", response.data.inspectionItems);
              this.inspectionItems = response.data.inspectionItems;
              this.itemsLoading = false;
              return;
            }
          } else {
            // 旧的数据结构
            plan = response.data;
            configId = plan.configId;
            console.log("使用旧的数据结构获取巡检计划信息:", plan);
          }
          
          // 确定配置ID
          if (configId) {
            // 使用配置ID获取巡检项
            this.getItemsByConfigId(configId);
          } else {
            // 尝试使用巡检记录中的configId
            if (this.inspectionRecord.configId) {
              console.log("使用巡检记录中的configId:", this.inspectionRecord.configId);
              this.getItemsByConfigId(this.inspectionRecord.configId);
            } else {
              console.warn("无法找到巡检配置ID");
              this.itemsLoading = false;
            }
          }
        } else {
          console.warn("获取巡检计划信息失败");
          // 尝试使用巡检记录中的configId
          if (this.inspectionRecord.configId) {
            console.log("使用巡检记录中的configId:", this.inspectionRecord.configId);
            this.getItemsByConfigId(this.inspectionRecord.configId);
          } else {
            this.itemsLoading = false;
          }
        }
      }).catch(error => {
        console.error("获取巡检计划出错", error);
        // 尝试使用巡检记录中的configId
        if (this.inspectionRecord.configId) {
          console.log("使用巡检记录中的configId:", this.inspectionRecord.configId);
          this.getItemsByConfigId(this.inspectionRecord.configId);
        } else {
          this.itemsLoading = false;
        }
      });
    },
    
    /** 根据配置ID获取巡检项 */
    getItemsByConfigId(configId) {
      getItemsByConfigId(configId).then(response => {
        if (response.code === 200 && response.data) {
          console.log("成功获取巡检配置项:", response.data);
          
          // 使用配置中的巡检项作为模板
          this.inspectionItems = response.data.map(item => {
            return {
              ...item,
              recordId: this.inspectionRecord.recordId,
              result: null,
              remark: ''
            };
          });
        } else {
          console.warn("获取巡检配置项失败");
        }
        this.itemsLoading = false;
      }).catch(error => {
        console.error("获取巡检配置项出错", error);
        this.itemsLoading = false;
      });
    },

    /** 获取巡检日期记录 */
    getDateRecords(recordId) {
      this.dateRecordsLoading = true;
      console.log("开始获取巡检日期记录，recordId:", recordId);
      
      getByInspectionRecord(recordId).then(response => {
        console.log("获取巡检日期记录响应:", response);
        
        if (response.code === 200) {
          this.dateRecords = response.data || [];
          // 按日期排序
          this.dateRecords.sort((a, b) => {
            return new Date(a.inspectionDate) - new Date(b.inspectionDate);
          });
          console.log("处理后的巡检日期记录:", this.dateRecords);
        } else {
          console.warn("获取巡检日期记录失败");
          this.dateRecords = [];
        }
        this.dateRecordsLoading = false;
      }).catch(error => {
        console.error("获取巡检日期记录出错", error);
        this.dateRecords = [];
        this.dateRecordsLoading = false;
      });
    },
    
    /** 状态翻译 */
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    
    /** 获取状态样式类型 */
    getStatusType(status) {
      switch (status) {
        case '0': return 'info';    // 待巡检
        case '1': return 'warning'; // 巡检中
        case '2': return 'success'; // 已完成
        case '3': return 'danger';  // 已取消
        default: return 'info';
      }
    },
    
    /** 选择字典标签 */
    selectDictLabel(options, value) {
      const option = options.find(item => item.dictValue === value);
      return option ? option.dictLabel : '';
    },
    
    /** 返回按钮操作 */
    goBack() {
      // 判断是否从列表页进入
      if (this.$route.query.fromList) {
        this.$router.push({ 
          path: '/sb/Inspection-list',
          query: { refresh: true }
        });
      } else {
        this.$router.go(-1);
      }
    },

    /** 行点击事件 */
    handleRowClick(row) {
      this.currentDateRecord = row;
      this.detailDialogVisible = true;
      this.getDetailItems(row.recordId);
    },

    /** 获取巡检详情项 */
    getDetailItems(dateRecordId) {
      this.detailLoading = true;
      
      // 获取日期记录中的巡检详情
      getDetailsByRecordId(dateRecordId).then(response => {
        if (response.code === 200 && response.data && response.data.length > 0) {
          console.log("原始巡检详情项数据:", response.data);
          
          // 检查第一个巡检详情项的数据结构
          if (response.data.length > 0) {
            this.checkDetailItemStructure(response.data[0]);
          }
          
          // 处理巡检详情项
          this.dateDetailItems = response.data.map(item => {
            // 记录原始数据中的备注相关字段
            console.log("巡检项目:", item.itemName, 
              "abnormalDesc:", item.abnormalDesc, 
              "suggestion:", item.suggestion, 
              "remark:", item.remark);
            
            const remarkText = item.abnormalDesc || item.suggestion || item.remark || '';
            
            return {
              ...item,
              standardValue: item.standardValue || item.itemStandard || item.normalRange || '-',
              remark: remarkText
            };
          });
          console.log("处理后的巡检详情项:", this.dateDetailItems);
        } else {
          // 如果没有详情数据，尝试通过巡检单ID和日期获取
          this.tryGetByDate();
        }
        this.detailLoading = false;
      }).catch(error => {
        console.error("获取巡检详情项出错", error);
        // 尝试通过巡检单ID和日期获取
        this.tryGetByDate();
      });
    },
    
    /** 尝试通过日期获取巡检详情 */
    tryGetByDate() {
      if (!this.currentDateRecord.inspectionDate) {
        console.warn("没有巡检日期，无法获取详情");
        this.dateDetailItems = [];
        this.detailLoading = false;
        return;
      }
      
      const formattedDate = this.parseTime(this.currentDateRecord.inspectionDate, '{y}-{m}-{d}');
      console.log("尝试通过日期获取巡检详情:", this.inspectionRecord.recordId, formattedDate);
      
      getByDate(this.inspectionRecord.recordId, formattedDate).then(response => {
        if (response.code === 200 && response.data && response.data.detailList) {
          console.log("通过日期获取的原始巡检详情项数据:", response.data.detailList);
          
          // 检查第一个巡检详情项的数据结构
          if (response.data.detailList && response.data.detailList.length > 0) {
            this.checkDetailItemStructure(response.data.detailList[0]);
          }
          
          this.dateDetailItems = response.data.detailList.map(item => {
            // 记录原始数据中的备注相关字段
            console.log("巡检项目:", item.itemName, 
              "abnormalDesc:", item.abnormalDesc, 
              "suggestion:", item.suggestion, 
              "remark:", item.remark);
            
            const remarkText = item.abnormalDesc || item.suggestion || item.remark || '';
            
            return {
              ...item,
              standardValue: item.standardValue || item.itemStandard || item.normalRange || '-',
              remark: remarkText
            };
          });
          console.log("通过日期获取并处理后的巡检详情项:", this.dateDetailItems);
        } else {
          console.warn("通过日期获取巡检详情项失败");
          this.dateDetailItems = [];
        }
        this.detailLoading = false;
      }).catch(error => {
        console.error("通过日期获取巡检详情项出错", error);
        this.dateDetailItems = [];
        this.detailLoading = false;
      });
    },

    /** 检查巡检详情项的数据结构 */
    checkDetailItemStructure(item) {
      console.log("检查巡检详情项数据结构:", item);
      console.log("数据类型:", typeof item);
      
      // 列出所有属性及其值
      const keys = Object.keys(item);
      console.log("所有属性:", keys);
      
      // 检查特定属性
      console.log("itemName:", item.itemName);
      console.log("itemStandard:", item.itemStandard);
      console.log("standardValue:", item.standardValue);
      console.log("result:", item.result);
      console.log("abnormalDesc:", item.abnormalDesc);
      console.log("suggestion:", item.suggestion);
      console.log("remark:", item.remark);
      
      return item;
    },

    /** 查看详情 */
    handleViewDetail(row) {
      this.currentDateRecord = row;
      this.detailDialogVisible = true;
      this.getDetailItems(row.recordId);
    }
  }
};
</script>

<style scoped>
.form-content {
  padding: 10px 15px;
  border: 1px solid #e6ebf5;
  border-radius: 4px;
  background-color: #f9fafc;
  min-height: 50px;
  line-height: 1.5;
}
.action-buttons {
  margin-top: 20px;
  text-align: center;
}
.no-attachment {
  color: #909399;
  text-align: center;
  padding: 20px 0;
}
</style> 